using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;

public class WriteData : MonoBehaviour
{
    private void Start()
    {
        WriteRealmData();
    }

    private void WriteRealmData()
    {
        // 读取境界数据
        string[] realmData = File.ReadAllLines($"{Application.dataPath}/Data/RealmData.txt");
        realmData = realmData.Select(line => line.Trim()).ToArray();

        // 记录境界数据
        string curRealm = "", curRank = "";
        LinkedList<Realm> realms = new LinkedList<Realm>();
        for (int i = 0; i < realmData.Length; i++)
        {
            string line = realmData[i];
            // 空行
            if (line == "") continue;

            // 境界
            switch (line[0])
            {
                case '#':
                    curRealm = realmData[i][1..].Trim();
                    break;
                case '-':
                    curRank = realmData[i][1..].Trim();
                    break;
                case '~':
                    int curLevel = 1;
                    while (i < realmData.Length && realmData[i][0] == '~')
                    {
                        string[] layerData = realmData[i][1..].Trim().Split('~');
                        (string layer, int level, string expFormula, string BTCondition) =
                            (layerData[0], int.Parse(layerData[1]), layerData[2], layerData[3]);
                        while (curLevel <= level)
                        {
                            Number curLevelNumber = new Number(Convert.ToString(curLevel), true, 0, true);
                            Number exp = Calculator.AnalyzeFormula(expFormula, curLevelNumber);
                            Realm realm = new Realm(
                                curRealm, curRank, layer, curLevel, exp, BTCondition
                            );
                            realms.AddLast(realm);
                            curLevel++;
                        }
                        i++;
                    }
                    i--;
                    break;
                default:
                    break;
            }
        }

        // 将最后一个境界设置为无限
        if (realms.Last.Value != null)
        {
            realms.Last.Value.exp = Number.Inf;
        }

        using var stream = new FileStream(Constant.REALM_DATA_PATH, FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, realms);
        print("写入境界数据成功");
    }
}